package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
//@Transactional mongodb事务必须是复制集方式
public class RegionServiceImpl implements IRegionService{


    @Autowired
    private RegionRepository repository;


    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //查询对象
        Query query = new Query();

        Long total = template.count(query, Region.class);
        if(total == 0){
            return Page.empty();//空的分页对象
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"_id");
        return DBHelper.query(template,Region.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            //更新
            //页面更新的数据,刚好和集合中字段个数一致
            //这种操作等价于全量更新
            this.update(region);
        }else {
            //保存
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {
        //查询
        Region region = this.get(id);
        //替换
        region.setIshot(hot);
        //更新
        this.update(region);
    }

    @Override
    public List<Region> queryHotRegion() {
        //状态是热门的
        //通过序号排序
        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
